<?php

namespace App\Kuafu\Brand\Service;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Brand\Enum\BrandCodeEnum;
use App\Kuafu\Brand\Exception\BrandException;
use App\Kuafu\Brand\Model\Brand;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\User\Service\UserRoleService;

class BrandService extends BaseService
{
    /**
     * 添加品牌
     * @param $request
     */
    public static function addBrand($request)
    {
        $brand            = new Brand();
        $brand->name      = $request->name;
        $brand->imageUrl  = $request->imageUrl;
        $brand->createdAt = time();
        $brand->updatedAt = time();
        try {
            $brand->save();
        } catch (\Exception $exception) {
            throw new BrandException(BrandCodeEnum::ERR_SERVER_ERROR, '添加失败，请稍后重试', $exception);
        }
    }

    /**
     * 获取品牌列表
     * @param $request
     */
    public static function getBrandList($request): array
    {
        try {
            //获取用户id
            $userId = AuthService::getUserId();
            if (!$userId) {
                throw new \Exception(
                    UserCodeEnum::CODE_TEXT[UserCodeEnum::ERR_USER_NOT_EXIST],
                    UserCodeEnum::ERR_USER_NOT_EXIST
                );
            }

            $brandIdListReturn = UserRoleService::getUserBrandIdList($userId);
            $brandIdListInfo   = self::getBrandListByIds($brandIdListReturn);

            return self::returnData(BrandCodeEnum::OK, '', $brandIdListInfo);
        } catch (\Exception $exception) {
            return self::returnData($exception->getCode(), $exception->getMessage());
        }
    }

    /**
     * 根据品牌ids 获取品牌详情
     *
     * @param array $idList
     * @return array
     */
    public static function getBrandListByIds(array $idList): array
    {
        $brand = new Brand();

        $brandList = $brand::query()->find($idList, ['id', 'name', 'imageUrl', 'status'])->toArray();

        return $brandList;
    }

    /**
     * 获取品牌详情
     * @param $request
     * @return mixed
     */
    public static function getBrandInfo($request)
    {
        return Brand::find($request->brandId);
    }

    /**
     * 修改品牌信息
     * @param $request
     * @throws BrandException
     */
    public static function setBrandInfo($request)
    {
        $data = [
            "name"      => $request->name,
            "imageUrl"  => $request->imageUrl,
            'updatedAt' => time()
        ];
        $id   = Brand::setBrandInfoById($request->brandId, $data);
        if (!$id) {
            throw new BrandException(BrandCodeEnum::ERR_UPDATE);
        }
    }

    /**
     * 删除品牌（软删除）
     * @param $request
     * @throws BrandException
     */
    public static function isDeletedBrand($request)
    {
        $id = Brand::setBrandInfoById($request->brandId, ['isDeleted' => 1]);
        if (!$id) {
            throw new BrandException(BrandCodeEnum::ERR_DELETED);
        }
    }

    /**
     * 品牌状态
     * @param $request
     */
    public static function setBrandStatus($request)
    {
        $id = Brand::setBrandInfoById($request->brandId, ['status' => $request->status]);
        if (!$id) {
            throw new BrandException(BrandCodeEnum::ERR_UPDATE);
        }
    }

    /**
     * 通过用户 Id 获取品牌列表
     *
     * @param int $userId
     * @return array
     */
    public static function getBrandListByUserId(int $userId): array
    {
        $brandIdListReturn = UserRoleService::getUserBrandIdList($userId);

        $brandIdListInfo = self::getBrandListByIds($brandIdListReturn);

        foreach ($brandIdListInfo as &$brandList) {
            $brandList['imageUrl'] = CommonService::joinImageUrl($brandList['imageUrl']);
        }
        return $brandIdListInfo;
    }
}
